<template>
	<view>
		<!-- 视频区 -->
		<view class="play-box">
			<block v-if="watchState == 1">
				<!-- #ifdef H5 -->
				<view class="iframe-player-box" v-if="video.use_type=='bilibili'" v-html="video.url"></view>
				<view class="player-container" id="player-container" v-else>
				</view>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS || MP-WEIXIN -->
				<web-view class="iframe-player-box" v-if="video.use_type=='bilibili'" :src="appWebviewVideoUrl">
				</web-view>
				<video id="myVideo" :src="video.url" :poster="poster" :title="video.title" ref="video"
					:poster-for-crawler="course.thumb" @ended="playEnd" object-fit='contain' :enable-danmu="true"
					:danmu-list="danmuList" :auto-pause-if-navigate="false" :auto-pause-if-open-native="false"
					v-else></video>
				<!-- #endif -->
			</block>
			<block v-if="watchState == 2">
				<view class="no-auth" @click="buyCourse">
					<text class="btn">请先报名</text>
				</view>
			</block>
		</view>
		<!-- 课程介绍 -->
		<view class="course-info">
			<view class="course-title">
				{{video.title}}
			</view>
			<view class="course-desc">
				简介：{{video.short_description}}
			</view>
			<!-- #ifdef APP-PLUS || MP-WEIXIN -->
			<view class="play-rate">
				<text>倍速：</text>
				<view class="rate-item" :class="playbackRate == index ? 'active' : ''" v-for="(item,index) in rate"
					:key="item" @click="changeRate(item,index)">
					{{item}} X
				</view>
			</view>
			<!-- #endif -->
		</view>
		<view class="course-tabs">
			<u-tabs-swiper ref="uTabs" active-color="#FF4B4B" :list="list" :current="current" @change="tabsChange"
				:is-scroll="false" swiperWidth="750"></u-tabs-swiper>
		</view>
		<swiper duration="200" class="swiper-item-box" :current="swiperCurrent" @transition="transition"
			@animationfinish="animationfinish">
			<swiper-item class="swiper-item">
				<scroll-view scroll-y>
					<view class="chapters">
						<block v-if="vk.pubfn.isNotNull(chapters)">
							<view class="chapter-item" v-for="(chapter,index) in chapters" :key="chapter._id">
								<view class="chapter-name">{{chapter.title}}</view>
								<view class="video-item" v-for="(item,index2) in chapter.videos" :key="item._id"
									@click="goVideo(item._id,index,index2)">
									<view class="name" :class="video._id == item._id ? 'active' : ''">
										<text class="free">视频</text>
										<text class="free" v-if="item.free_seconds && !isBuy">试看</text>
										<text class="video-name">{{item.title}}</text>
									</view>
									<view class="duration" v-if="video._id == item._id && isBuy">
										<image src="@/static/liveing.gif" mode="widthFix"></image>
									</view>
									<view class="duration" v-else>
										<block v-if="vk.pubfn.isNotNull(item.watch_info)">已看完</block>
										<block v-else>{{item.duration | durationForHuman}}</block>
									</view>
								</view>
							</view>
						</block>
						<empty v-else :tipText="'暂未更新课程'"></empty>
					</view>
				</scroll-view>
			</swiper-item>
			<swiper-item class="swiper-item">
				<scroll-view scroll-y>
					<u-parse :html="video.render_desc"></u-parse>
				</scroll-view>
			</swiper-item>
			<swiper-item class="swiper-item">
				<scroll-view scroll-y>
					<view class="chapters">
						<block v-if="vk.pubfn.isNotNull(chapters)">
							<u-collapse event-type="close" :arrow="true" :accordion="false">
								<u-collapse-item :index="index" :title="item.title" v-for="(item, index) in chapters"
									:key="item._id">
									<view class="collapse-item collapse-item-word" v-if="vk.pubfn.isNotNull(item.word)"
										@click="checkPdf(item.word.url)">
										<view class="u-node"></view>
										{{item.word.title}}
									</view>
									<view class="collapse-item" v-else>
										暂无讲义
									</view>
								</u-collapse-item>
							</u-collapse>
						</block>
						<empty v-else :tipText="'暂未更新讲义'"></empty>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>


	</view>
</template>

<script>
	import util from '@/utils/util'
	import DPlayer from '@/static/jslib/DPlayer.min.js'
	var that
	const app = getApp();

	export default {
		data() {
			return {
				appWebviewVideoUrl: '',
				playOptions: [],
				video: {
					title: "",
					short_description: ""
				},
				course: {
					thumb: null
				},
				chapters: [],
				videos: [],
				attachs: [],
				navTab: 'menu',
				isBuy: false,
				videoWatchedProgress: [],
				comments: [],
				commentUsers: [],
				videoId: 0,
				courseId: 0,
				commentContent: '',
				playInfo: [],
				playUrl: '',
				poster: '',
				lastPlaySeconds: 0,
				isIos: util.isIos(),
				list: [{
					name: '课程目录'
				}, {
					name: '视频介绍'
				}, {
					name: '讲义目录'
				}],
				current: 0,
				swiperCurrent: 0,
				videoContext: null,
				playbackRate: 2,
				rate: [0.5, 0.8, 1.0, 1.25, 1.5],
				danmuList: [],
				watchState: 0,
				// 记录位置
				cIndex: 0,
				vIndex: 0,
				newconfig: {
					player: {
						enabled_bullet_secret: 0,
						bullet_secret: {
							text: ''
						}
					}
				}
			};
		},
		filters: {
			durationForHuman(data) {
				return util.durationForHuman(data)
			}
		},
		computed: {
			isTrySee() {
				return !that.isBuy && this.video.free_seconds > 0
			},
			isBanDrag() {
				return this.video.ban_drag
			}
		},
		onLoad: function(options) {
			that = this
			this.courseId = options.course_id
			this.videoId = options.video_id
			this.poster = app.globalData.player_cover

			this.getCourse();
		},
		methods: {
			DPlayerDestroy() {
				// #ifdef H5
				if (window.player) {
					window.player.destroy();
				}
				// #endif
			},
			getCourse() {
				uni.vk.callFunction({
					url: 'client/course/pub/detail',
					title: '获取课程列表',
					data: {
						_id: this.courseId,
						need_user_info: true
					},
					success(res) {
						// 	// 富文本图片溢出
						if (res.data.courses.render_desc)
							res.data.courses.render_desc = res.data.courses.render_desc.replace(/\<img/gi,
								'<img style="max-width:100%;height:auto;display:block;" ');

						that.course = res.data.courses
						that.chapters = res.data.test

						that.isBuy = res.data.has_buy
						that.getVideo();
					}
				});
			},
			changeRate(rate, index) {
				this.playbackRate = index
				this.videoContext.playbackRate(this.rate[this.playbackRate])
			},
			getVideo() {
				uni.showLoading({
					title: "视频加载中..."
				})
				uni.vk.callFunction({
					url: 'client/course/pub/video_detail',
					data: {
						course_id: this.courseId,
						video_id: this.videoId,
						need_user_info: true
					},
					success: (res) => {
						uni.setNavigationBarTitle({
							title: res.data.video.title,
						})
						// 	// 富文本图片溢出
						if (res.data.video.render_desc)
							res.data.video.render_desc = res.data.video.render_desc.replace(/\<img/gi,
								'<img style="max-width:100%;height:auto" ');

						let video = res.data.video
						if (video.use_type == 'bilibili' && video.url) {
							video.url = video.url.replace(
								">",
								' style="width:100%;height:210px" >'
							);
						}

						that.video = video
						if (that.isBuy || video.free_seconds > 0) {
							that.watchState = 1
						} else {
							that.watchState = 2
						}

						// #ifdef APP-PLUS || MP-WEIXIN
						if (video.use_type != 'bilibili') {
							this.videoContext = uni.createVideoContext('myVideo', this)
							this.playbackRate = 2
							this.videoContext.playbackRate(1.0)
							setTimeout(function() {
								that.$forceUpdate()
								that.videoContext.play()
							}, 1000)
						} else {
							this.appWebviewVideoUrl = this.video.url.match(/\/\/[^"'\s]*/)[0]
							let currentWebview = this.$scope.$getAppWebview(); //获取当前web-view  
							let duration_timeout = setTimeout(function() {
								let wv = currentWebview.children()[0];
								console.log(wv);
								wv.setStyle({
									//设置web-view距离顶部的距离以及自己的高度，单位为px  
									top: uni.getSystemInfoSync().statusBarHeight + 43,
									height: 210
									/* left: 80,  
									width: 1120,  
									height: 630, */
								});
								clearTimeout(duration_timeout);
							}, 500);
						}
						// #endif

						// #ifdef H5
						if (video.use_type != 'bilibili') {
							setTimeout(function() {
								that.$forceUpdate()
								that.initDPlayer({
									name: video.title,
									url: video.url
								}, res.data.videoBase || {});
							}, 1000)
						}
						// #endif

						uni.hideLoading()
					},
					fail(e) {
						uni.hideLoading()
					}
				});
			},
			initDPlayer(playUrls, videoBase) {
				// 封装DPlayer的播放格式
				// let dplayerUrls = [];
				// playUrls.forEach((item) => {
				// 	dplayerUrls.push({
				// 		name: item.name,
				// 		url: item.url,
				// 	});
				// });

				let bulletSecretFontSize = !this.newconfig.player.bullet_secret.size ?
					14 :
					parseInt(this.newconfig.player.bullet_secret.size);

				// window.player = new DPlayer({
				// 	container: document.getElementById('player-container'),
				// 	video: {
				// 		url: playUrls.url,
				// 	},
				// });

				window.player = new DPlayer({
					container: document.getElementById("player-container"),
					autoplay: false,
					playbackSpeed: [0.5, 1, 1.5, 2],
					video: {
						url: playUrls.url,
						// defaultQuality: 0,
						pic: this.newconfig.player.cover || null,
					},
					try: this.isTrySee,
					bulletSecret: {
						enabled: parseInt(this.newconfig.player.enabled_bullet_secret) === 1,
						text: this.newconfig.player.bullet_secret.text
							.replace("${user.mobile}", vk.getVuex('$user.userInfo')?.mobile)
							.replace("${mobile}", vk.getVuex('$user.userInfo')?.mobile)
							.replace("${user.id}", vk.getVuex('$user.userInfo')?._id),
						size: bulletSecretFontSize + "px",
						color: !this.newconfig.player.bullet_secret.color ?
							"red" : this.newconfig.player.bullet_secret.color,
						opacity: this.newconfig.player.bullet_secret.opacity,
					},
					ban_drag: this.isBanDrag,
					last_see_pos: 0,
				});

				// 监听播放进度更新evt
				window.player.on("timeupdate", () => {
					let currentTime = parseInt(window.player.video.currentTime);
					if (
						this.isBanDrag &&
						currentTime - this.lastPlaySeconds >= 2 &&
						currentTime > parseInt(this.watchedSeconds)
					) {
						window.player.seek(this.lastPlaySeconds);
					} else {
						this.lastPlaySeconds = currentTime;
						// this.playTimeUpdate(currentTime);
					}
				});
				window.player.on("ended", () => {
					let currentTime = parseInt(window.player.video.currentTime);
					if (
						this.isBanDrag &&
						window.player.video.duration - this.lastPlaySeconds >= 2
					) {
						window.player.seek(this.lastPlaySeconds);
						return;
					}
					this.lastPlaySeconds = 0;
					// this.playTimeUpdate(currentTime, true);
					this.playEnd()
					this.playendedStatus = true;
					window.player.destroy();
				});
				window.player.on("sub_course", () => {
					this.buyCourse();
				});
				// 微信同层播放
				setTimeout(() => {
					const dplay = document.querySelector(".dplayer-video");
					const u = navigator.userAgent;
					let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
					if (isAndroid) {
						dplay.setAttribute("x5-video-player-type", "h5-page");
						dplay.removeAttribute("playsinline");
						dplay.removeAttribute("webkit-playsinline");
					} else {
						dplay.removeAttribute("x5-video-player-type", "h5-page");
						dplay.setAttribute("playsinline", "");
						dplay.setAttribute("webkit-playsinline", "");
					}
				}, 200);
			},
			getPlayInfo() {
				video.playUrl(this.video.id).then(res => {
					if (res.urls.length === 0) {
						uni.showToast({
							icon: 'none',
							title: '播放地址为空',
						})
					} else {
						this.playInfo = res.urls
						this.playUrl = res.urls[0].url

						//记忆播放功能
						this.videoContext.play()

						if (this.videoWatchedProgress[this.video.id] && this.videoWatchedProgress[this.video.id]
							.watched_at == null) {
							this.videoContext.seek(this.videoWatchedProgress[this.video.id].watch_seconds)
							uni.showToast({
								title: "已为您定位至 " + util.durationForHuman(this.videoWatchedProgress[this
									.video.id].watch_seconds),
								icon: "none"
							})
						}

					}
				})
			},

			goVideo(videoId, cIndex, vIndex) {
				//切换视频
				this.videoId = videoId
				this.getVideo()

				//重置播放器
				// #ifdef APP-PLUS || MP-WEIXIN
				this.playbackRate = 2
				this.videoContext.playbackRate(1.0)
				this.videoContext.stop()
				// #endif

				// #ifdef H5
				if (window.player)
					window.player.destroy();
				// #endif

				// 记录位置
				this.cIndex = cIndex
				this.vIndex = vIndex
			},

			playEnd(e) {
				// 没买不存
				if (!that.isBuy) return

				uni.vk.callFunction({
					url: 'client/course/kh/records',
					data: {
						course_id: this.courseId,
						video_id: this.videoId,
						watch_seconds: this.lastPlaySeconds,
						watched_at: 1
					},
					success: function() {
						// 状态暂时改为已看完
						that.chapters[that.cIndex].videos[that.vIndex].watch_info = {
							_id: '123456'
						}
					}
				})
			},
			buyCourse() {
				//先创建订单
				uni.vk.callFunction({
					url: 'client/order/kh/create/course',
					data: {
						_id: this.courseId
					},
					success(data) {
						//再前往支付
						uni.vk.navigateTo('/pages/payment/payType?order_id=' + data.order_id)
					}
				});
			},
			checkPdf(url) {
				if (!that.isBuy) {
					this.$refs.uToast.show({
						title: '购买课程后即可查看',
						type: 'warning',
					})
					return
				}
				uni.vk.navigateTo(`/uni_modules/uce-course/pages/word/word?url=${url}`)
			},
			// tabs通知swiper切换
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.uTabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f2f2f2;
	}


	.play-box {
		position: relative;
		width: 100%;
		height: 210px;
		float: left;
		background-color: rgba(0, 0, 0, 1);
	}

	.xgplayer-mobile {
		padding-top: 50% !important;
	}

	.xgplayer-skin-default .xgplayer-poster {
		height: 192px !important;
		overflow: hidden;
	}

	.iframe-player-box,
	.player-container,
	.video {
		width: 100%;
		height: 420rpx;
	}

	.play-box>video {
		width: 100%;
		height: 240px;
	}

	.play-box>.no-auth {
		width: 100%;
		height: auto;
		box-sizing: border-box;
		padding-left: 30px;
		padding-right: 30px;
	}

	.play-box>.no-auth>.btn {
		display: inline-block;
		width: 100%;
		height: 42px;
		line-height: 42px;
		text-align: center;
		background-color: rgba(0, 0, 0, .9);
		color: #FF4B4B;
		border: 1px solid #FF4B4B;
		border-radius: 21px;
		margin-top: 70px;
	}

	.course-info {
		position: relative;
		width: 100%;
		min-height: 150rpx;
		background: #FFFFFF;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 30rpx;

		.play-rate {
			width: 100%;
			height: 60rpx;
			display: flex;
			justify-content: left;
			align-items: center;

			text {
				color: #333333;
				line-height: 40rpx;
			}

			.rate-item {
				width: 90rpx;
				height: 40rpx;
				border-radius: 10rpx;
				line-height: 38rpx;
				font-size: 20rpx;
				text-align: center;
				border: 1rpx solid #ACAFC3;
				color: #ACAFC3;
				margin-right: 24rpx;
				font-weight: bold;
			}

			.active {
				color: #000 !important;
				background-color: #CCDEFF !important;
				border: 1rpx solid #CCDEFF;
			}
		}

		.course-title {
			font-size: 32rpx;
			font-weight: 800;
			color: #000000;
		}

		.course-desc {
			margin: 20rpx 0;
			color: #555555;
			font-size: 28rpx;
			text-align: justify;
			overflow: hidden;
			display: -webkit-box;
			text-overflow: ellipsis;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
		}

		.course-other {
			color: #B7BACA;
			font-size: 25rpx;

			text {
				margin-right: 40rpx;
			}
		}
	}

	.course-tabs {
		margin-top: 10rpx;
		position: sticky;
		top: 0;
		background: #FFFFFF;
		z-index: 999;
	}


	.swiper-item-box {
		position: relative;
		height: 100vh;

		.swiper-item {
			border-top: 1px solid #efefef;
			background: #FFFFFF;
			position: relative;

			scroll-view {
				height: 100% !important;
			}
		}
	}

	.course-like {
		position: absolute;
		bottom: 30rpx;
		right: 40rpx;
	}

	.buy-foot,
	.comment-bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 100rpx;
		width: 750rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		justify-content: space-between;
		box-shadow: 0px 0px 10px #B2B5C6;

		.charge {
			color: #F11C1C;
			font-size: 36rpx;
			font-weight: bold;
		}

		.buy-btn-box {
			padding: 0 20rpx;
			display: flex;
			align-items: center;

			.vip-tip {
				margin: 0 20rpx;
				font-size: 30rpx;
				letter-spacing: 2rpx;
				font-weight: bold;
				color: #FE9521;
			}

			.buy-btn {
				width: 180rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				border-radius: 35rpx;
				background-image: linear-gradient(to right, #FF104B, #FF785F);
				color: #FFFFFF;
				font-size: 26rpx;
				font-weight: bold;
				letter-spacing: 2rpx;
			}
		}

	}

	.chapters {
		padding: 20rpx 30rpx;

		.chapter-name {
			width: 100%;
			height: auto;
			float: left;
			font-size: 15px;
			color: #333;
			font-weight: 700;
			margin-bottom: 15px;
			margin-top: 10px;
		}

		.video-item {
			width: 100%;
			height: auto;
			float: left;
			display: flex;
			margin-bottom: 20rpx;
			line-height: 60rpx;
			box-sizing: border-box;
			padding-left: 5px;
			border-bottom: 1rpx dashed #efefef;

			.active {
				color: #FF4B4B !important;
				font-weight: bold !important;
			}

			.name {
				-webkit-box-flex: 1;
				-webkit-flex: 1;
				flex: 1;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				font-size: 14px;
				color: rgba(51, 51, 51, .8);

				.video-name {
					font-size: 30rpx;
					width: 490rpx;
				}

				.free {
					padding: 2px 4px;
					background-color: #FF4B4B;
					-webkit-border-radius: 3px;
					border-radius: 3px;
					color: #fff;
					font-size: 12px;
					margin-right: 5px;
				}

				.lock-fill {
					&:before {
						content: "";
					}
				}
			}

			.duration {
				width: auto;
				height: auto;
				font-size: 12px;
				margin-left: 10px;
				color: #999;

				image {
					position: relative;
					top: 10rpx;
					display: inline-block;
					width: 28rpx;
					height: 20rpx;
					margin-left: 20rpx;
				}
			}
		}
	}

	.comment {
		display: flex;
		padding: 30rpx;

		.left {
			image {
				width: 64rpx;
				height: 64rpx;
				border-radius: 50%;
				background-color: #f2f2f2;
			}
		}

		.right {
			flex: 1;
			padding-left: 20rpx;
			font-size: 30rpx;

			.top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 10rpx;

				.name {
					color: #000000;
					font-weight: 500;
				}
			}

			.content {
				margin-bottom: 10rpx;
			}
		}
	}


	.comment-bottom-bar>.input {
		flex: 1;
	}

	.comment-bottom-bar>.input>input {
		width: 100%;
		height: 30px;
		float: left;
		background: rgba(238, 238, 238, 1);
		border-radius: 18px;
		border: 0;
		box-sizing: border-box;
		padding: 3px 15px;
		font-size: 12px;
	}

	.comment-bottom-bar>.send-button {
		margin-left: 15px;
		font-size: 13px;
		font-weight: 400;
		color: rgba(204, 204, 204, 1);
		line-height: 30px;
	}

	.comment-bottom-bar>.send-button.active {
		color: rgba(23, 132, 237, 1);
		font-weight: bold;
	}

	.chapters {
		padding: 20rpx 30rpx;

		.collapse-item {
			padding: 10rpx 40rpx 0;

			.u-node {
				width: 20rpx;
				height: 20rpx;
				background: #FFFFFF;
				border: 2rpx solid #FDD303;
				border-radius: 50%;
			}

			.study_status {
				width: 120rpx;
				border: 2rpx solid #333333;
				border-radius: 26rpx;
				position: absolute;
				text-align: center;
				font-size: 24rpx;
				font-weight: bold;
				line-height: 38rpx;
				color: #333333;
				top: 28rpx;
				right: 0;
			}
		}

		.collapse-item-word {
			padding: 30rpx 40rpx;
			display: flex;
			align-items: center;

			.u-node {
				margin-right: 10rpx;
			}
		}
	}
</style>